<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace common\behavior;

use common\model\EntityEpisodeRelationModel;
use common\service\AsyncCallService;
use common\service\StatusService;
use common\model\EntityModel;
use think\Exception;

/**
 * 行为扩展：计算预估工时
 */
class FillEntityDefaultDataBehavior
{
    /**
     * 计算工时
     * @param $params
     * @return void
     * @throws Exception
     */
    public function run(&$params)
    {
        $entityId = $params['pk'];
        $entityData = model(EntityModel::class)->find($entityId);
        // 处理实体默认状态
        $entityData['json'] = json_decode($entityData['json'], true);
        $this->checkEntityDefaultStatus($entityData);
        // 添加实体剧集关系
        $this->addEntityRelationData($entityData);
        // 检查关联关系 存储到实体关联表
        AsyncCallService::getInstance()->syncRelationDataToEntityRelationShipsAsync($entityId, 3);
    }

    /**
     * 检查实体默认状态
     * @param $entityData
     */
    public function checkEntityDefaultStatus($entityData)
    {
        $currentModule = module_by_id($entityData['module_id']);
        $statusField = $currentModule['code'] . '_status';
        $status = $entityData['json'][$statusField] ?? null;
        /**
         * 只有分镜和概念需要设置默认 创作状态
         */
        if (!empty($status)) {
            return;
        }
        if (!in_array($currentModule['code'], ['design', 'storyboard'])) {
            return;
        }
        if ($currentModule['code'] === 'design') {
            // 待发布
            $entityDefaultStatus = StatusService::getInstance()->getOne(['code' => 'ready_to_publish'], 'id');
        } else {
            // 待组装序列
            $entityDefaultStatus = StatusService::getInstance()->getOne(['code' => 'wait_for_merge_sequence'], 'id');
        }
        if (empty($entityDefaultStatus)) {
            return;
        }
        APP_DEBUG && trace('update entity status to ' . $entityDefaultStatus['id'], 'DEBUG');
        model(EntityModel::class)->execute("update entity set json = json_set(IFNULL(json,'{}'),'$.{$statusField}',{$entityDefaultStatus['id']}) where id = {$entityData['id']}");
    }

    /**
     * 添加实体剧集关系
     * @param $entityData
     * @return void
     * @throws \Exception
     */
    private function addEntityRelationData($entityData)
    {
        $episode = model(EntityModel::class)
            ->where(['project_id' => $entityData['project_id'], 'module_id' => module_by_code('episode')['id'], 'code' => $entityData['initial_episode_code']])
            ->cache(50)
            ->find();
        if (empty($episode)) {
            return;
        }
        $addData = [
            'entity_id' => $entityData['id'],
            'entity_module_id' => $entityData['module_id'],
            'project_id' => $entityData['project_id'],
            'episode_id' => $episode['id'],
            'showings_number' => $entityData['showings_number'] ?? ''
        ];
        model(EntityEpisodeRelationModel::class)->addItem($addData);
        APP_DEBUG && trace(__METHOD__ . "添加实体集关系 {$entityData['initial_episode_code']}-{$addData['showings_number']}-{$entityData['name']}", 'DEBUG');
    }
}
